﻿<%@ Page Language="C#" AutoEventWireup="true" %>

<% 
    if (System.Web.HttpRuntime.Cache["pre_auth_code_expires"] == null)
    {
        weixin.api.WXComponent.GetPreAuthCode();
    }
    if (string.IsNullOrEmpty(Request.QueryString["auth_code"]))
    {
        Response.Redirect(string.Format("https://mp.weixin.qq.com/cgi-bin/componentloginpage?component_appid={0}&pre_auth_code={1}&redirect_uri={2}",
            weixin.api.WXConfig.sAppID,
            System.Web.HttpRuntime.Cache["pre_auth_code"],
            System.Web.HttpUtility.UrlEncode(Request.Url.AbsoluteUri)
        ));
    }
    else
    {
        string auth_code = Request.QueryString["auth_code"];
        weixin.api.DeserializeJson dic = weixin.api.WXComponent.GetAuthorizationInfo(auth_code);
        string authorizer_appid = dic.GetString("authorization_info.authorizer_appid");
        if (!string.IsNullOrEmpty(authorizer_appid))
        {
            string authorizer_access_token = dic.GetString("authorization_info.authorizer_access_token");
            string authorizer_refresh_token = dic.GetString("authorization_info.authorizer_refresh_token");
            dic = weixin.api.WXComponent.GetAuthorizerAccountInfo(authorizer_appid);

            weixin.Services.WeixinMpsService service = new weixin.Services.WeixinMpsService();
            weixin.Models.tb_WeixinMps model = service.GetByAppId(authorizer_appid) ?? new weixin.Models.tb_WeixinMps() { id = 0, updatetime = DateTime.Now };
            model.appid = dic.GetString("authorization_info.authorizer_appid");
            model.access_token = authorizer_access_token;
            model.refresh_token = authorizer_refresh_token;
            model.nick_name = dic.GetString("authorizer_info.nick_name");
            model.head_img = dic.GetString("authorizer_info.head_img");
            model.user_name = dic.GetString("authorizer_info.user_name");
            model.alias = dic.GetString("authorizer_info.alias");
            model.qrcode_url = dic.GetString("authorizer_info.qrcode_url");
            model.principal_name = dic.GetString("authorizer_info.principal_name");
            model.signature = dic.GetString("authorizer_info.signature");
            //model.access_token = dic.GetString("authorizer_info.authorizer_appid");
            //model.refresh_token = dic.GetString("authorizer_info.refresh_token");
            service.AddOrUpdate(model);
            System.Web.HttpRuntime.Cache.Remove("pre_auth_code_expires");
            System.Web.HttpRuntime.Cache.Remove("pre_auth_code");
        }
    }
%>